package services.tutor;

import models.permission.User;
import models.tutor.Tutor;
import org.apache.commons.lang.StringUtils;
import play.db.jpa.JPA;
import utils.query.ModelQuery;
import utils.query.Page;

import javax.persistence.Query;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by FireFire on 6/26 0026.
 */
public class TutorService {

    /**
     * 得到当前登陆的导师信息
     * @param user
     * @return
     */
    public static Tutor currentUserRelatedTutor(User user){
        Tutor tutor = Tutor.find("byCode",user.userName).first();
        return tutor;

    }

    public static int pageSize = 15;

    /**
     * 根据院系，导师类型，当前页码返回导师列表数据
     * @param schoolName
     * @param page
     * @return
     */
    public static Page<Tutor> tutorList(String schoolName,String tutorType, int page){
        if(page<=0) page=1;
        String query = "select t from Tutor t where " +
                " t.unit=?";
        String countQuery = "select count(*) from Tutor t where t.unit=? ";
        if(StringUtils.isNotEmpty(tutorType)){
            query += " and t.tutorType=? ";
            countQuery += " and t.tutorType=? ";
        }
        query += " order by t.disciplineCode, t.name";

        List<Tutor> tutorList = new ArrayList();
        long count = 0;
        if(StringUtils.isNotEmpty(tutorType)) {
            tutorList = Tutor.find(query,
                    schoolName,tutorType).fetch(page,20);
            count = Tutor.count(countQuery, schoolName, tutorType);
        }else{
            tutorList = Tutor.find(query,
                    schoolName).fetch(page,20);
            count = Tutor.count(countQuery, schoolName);
        }
        Page<Tutor> currentPage = new Page();
        currentPage.list = tutorList;
        currentPage.totalCount = (int)count;
        currentPage.pageSize = 20;
        currentPage.currPage = page;
        return currentPage;
    }

    public static Page<Tutor> tutorListByMultiple(String name, int page){
        if(page<=0) page=1;
        String searchName = "%"+name+"%";

        String query = "select t from Tutor t where " +
                " t.unit like ? or t.tutorType like ? or t.name like ? order by t.disciplineCode, t.name";

        String countQuery = "select count(*) from Tutor t where " +
                " t.unit like ? or t.tutorType like ? or t.name like ? ";
        long count = Tutor.count(countQuery, searchName, searchName, searchName);

        List<Tutor> tutorList = Tutor.find(query,
                searchName,searchName,searchName).fetch(page,20);

        Page<Tutor> currentPage = new Page();
        currentPage.list = tutorList;
        currentPage.totalCount = (int)count;
        currentPage.pageSize = 20;
        currentPage.currPage = page;
        return currentPage;
    }
}
